package com.leff.cards.entity;

import java.util.ArrayList;

import com.leff.cards.Dictionary;
import com.leff.cards.StoreWrapper;

public class HistoryItem {

	public long queryCardId;
	public long userId;
	public ArrayList<String> allSubmissions;
	public String chosenSubmission;
	
	private HistoryItem() {
	}
	
	public Dictionary toJSON() {
		
		Dictionary obj = new Dictionary();
		
		QueryCard QC = StoreWrapper.getQueryCardById(queryCardId);
		obj.put("query", QC.toJSON());
		
		User U = StoreWrapper.getUserById(userId);
		obj.put("user", U.toJSON());
		
		ArrayList<ArrayList<Object>> allResponses = new ArrayList<ArrayList<Object>>();
		int chosenIndex = 0;
		int i = 0;
		for(String submission : allSubmissions) {
			ArrayList<ResponseCard> cards = StoreWrapper.getResponseCardsWithIdString(submission);
			ArrayList<Object> cardJsonObjs = new ArrayList<Object>();
			
			for(ResponseCard RC : cards) {
				cardJsonObjs.add(RC.toJSON());
			}
			
			allResponses.add(cardJsonObjs);
			
			if(submission.equals(chosenSubmission)) {
				chosenIndex = i;
			}
			i++;
		}
		
		obj.put("cards", allResponses);
		obj.put("winner", chosenIndex);
		
		return obj;
	}
	
	public static String encode(HistoryItem HI) {
		return encode(HI.queryCardId, HI.userId, HI.allSubmissions, HI.chosenSubmission);
	}
	public static String encode(long qcId, long userId, ArrayList<String> allCards, String chosenCards) {
		
		StringBuilder sb = new StringBuilder();
		
		sb.append(qcId).append(":");
		sb.append(userId).append(":");
		
		boolean first = true;
		for(String S : allCards) {
			if(!first) {
				sb.append("~");
			}
			sb.append(S);
			first = false;
		}
		sb.append(":").append(chosenCards);
		
		return sb.toString();
	}
	
	public static HistoryItem decode(String string) {
		
		HistoryItem HI = new HistoryItem();
		String[] parts = string.split(":");
		
		HI.queryCardId = Long.valueOf(parts[0]);
		HI.userId = Long.valueOf(parts[1]);
		
		String[] arr = parts[2].split("~");
		HI.allSubmissions = new ArrayList<String>();
		for(String S : arr) {
			HI.allSubmissions.add(S);
		}
		
		HI.chosenSubmission = parts[3];
		
		return HI;
	}
}
